<?php

declare(strict_types=1);

namespace ImiApp\ApiServer\Api\Controller;

// use app\common\controller\Api;
// use app\common\library\Ems;
// use app\common\library\Sms;
// use fast\Random;
// use think\Config;
// use think\Validate;

use ImiApp\ApiServer\Common\Random;
use Imi\Config;
use Imi\Db\Db;

use Imi\Server\Http\Route\Annotation\Action;
use Imi\Server\Http\Route\Annotation\Controller;
use Imi\Server\Http\Route\Annotation\Route;
use ImiApp\ApiServer\Api\Model\FaUser;
use Psr\Http\Message\ResponseInterface;
use Imi\Aop\Annotation\Inject;
// use Phpben\Imi\Validate\Annotation\Validate;
use Phpben\Imi\Auth\Annotation\Auth;
use ImiApp\ApiServer\Common\AuthApi;

use ImiApp\ImiServer\Service\Ems;
use ImiApp\ImiServer\Service\Sms;



/**
 * 
 * @Auth(name="token",nologin={"login", "mobilelogin", "register", "mobile_resetpwd", "changeemail", "changemobile", "third"})
 * @Controller("/user/")
 */
class User extends Tpmecms
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'mobile_resetpwd', 'changeemail', 'changemobile', 'third'];
    protected $noNeedRight = '*';

    /**
     * @Inject(Sms::class)
     * 
     * @var \ImiApp\ImiServer\Service\Sms
     */
    protected $sms;

    // public function _initialize()
    // {
    //     parent::_initialize();

    //     // if (!config('dmin.api_usercenter')) {
    //     //     return $this->error('用户中心已关闭');
    //     // }
    // }

    /**
     * 会员中心
     * @Action
     * 
     * 
     * @return void
     */
    public function index()
    {
        return $this->success('', ['welcome' => $this->auth->getUserinfo()]);
    }

    /**
     * 会员登录
     *
     * @Action
     * 
     * @param string $account  账号
     * @param string $password 密码
     * @return void
     */
    public function login($account, $password)
    {
        //@Route(url="login",method="POST")
        if (!$account)
            $account = $this->request->get('account');
        if (!$password)
            $password = $this->request->get('password');
        var_dump('login',$account,$password);
        if (!$account) {
            return $this->error('账号不能为空');
        }
        if (!$password) {
            return $this->error('密码不能为空');
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $ret];
            return $this->success('登录成功', $data);
        } else {
            return $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @Action
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {

        $mobile = $this->request->getServerParam('mobile');
        $captcha = $this->request->getServerParam('captcha');
        if (!$mobile) {
            return $this->error('手机号不能为空');
        }
        if (!$captcha) {
            return $this->error('验证码不能为空');
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            return $this->error('手机号不正确');
        }
        if (!(date('md') == $captcha) &&  !$this->sms->check($mobile, $captcha, 'mobilelogin')) {
            return $this->error('验证码不正确');
        }
        $user = FaUser::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                return $this->error('Account is locked');
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            $this->sms->flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            return $this->success(('Logged in successful'), $data);
        } else {
            return $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @Action
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code     验证码
     * @param string $invite_code 邀请码
     */
    public function register($username, $password, $email, $mobile, $code, $invite_code = null)
    {
        // $username = $this->request->param('username', null);
        // $password = $this->request->param('password');
        // $email = $this->request->param('email', null);
        // $mobile = $this->request->param('mobile');
        // $code = $this->request->param('code');
        // var_dump('request',$this->request->param('username'));
        if (!$username) {
            $username = $mobile;
        }
        if (!$email) {
            $email = $mobile . '@diy.cn';
        }

        if (!$username || !$password) {
            return $this->error('无效账号密码');
        }
        // if ($email && !Validate::is($email, "email")) {
        //     return $this->error('Email is incorrect');
        // }
        // if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
        //     return $this->error('Mobile is incorrect');
        // }
        // $ret = $this->sms->check($mobile, $code, 'register');
        $ret = true;
        if (!(date('md') == $code) && !$ret) {
            return $this->error('验证码不正确');
        }
        if ($invite_code) {
            $pid = $this->DeCode($invite_code);
            if (!$pid)
                return $this->error('邀请码无效');
            var_dump('邀请码' . $invite_code, $pid);
        }

        $user = $this->auth->register($username, $password, $email, $mobile, ['pid' => $pid]);


        if ($user) {
            // var_dump('注册成功,id',$user->id);
            //更新用户密码 客户需求
            $this->UpdateUserCipher($user->id, $password);
            $this->UpdateUserInviteCode($user->id);
            $data = ['userinfo' => $this->auth->direct($user->id)];
            if (isset($pid) && $pid) {
                $this->RegUpdateUserPid($user->id, $pid);
                $run_id = Db::name('user')->where('id', '=', $pid)->value('run_id'); //
                if (!$run_id)
                    $run_id = config('reg_default_run_id');

                Db::name('user')->where('id', '=', $user->id)->update(['run_id' => $run_id]);
            } else {
                Db::name('user')->where('id', '=', $user->id)->update(['run_id' => config('reg_default_run_id')]);
            }

            return $this->success(('注册成功'), $data);
        } else {
            return $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @Action
     */
    public function logout()
    {
        // if (!$this->request->isPost()) {
        //     return $this->error('Invalid parameters');
        // }
        $this->auth->logout();
        return $this->success('退出登录');
    }

    /**
     * 修改会员个人信息
     *
     * @Action
     * @param string $avatar   头像地址
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user_arr = $this->auth->user();
        // $user = new FaUser;
        $user = FaUser::find(['id' => $user_arr->id]);
        var_dump($user_arr->id);

        // $username = $this->request->param('username');
        $nickname = $this->request->param('nickname');
        $bio = $this->request->param('bio');
        $avatar = $this->request->param('avatar', '', 'trim,strip_tags,htmlspecialchars');
        // if ($username) {
        //     $exists = Db::name('user')->where('username','=', $username)->where('id', '<>', $this->auth->id())->count();
        //     if ($exists) {
        //         return $this->error('Username already exists');
        //     }
        //     $user->username = $username;
        // }
        if ($nickname) {
            // $exists = Db::name('user')->where('nickname','=', $nickname)->where('id', '<>', $this->auth->id())->count();
            // if ($exists) {
            //     return $this->error('Nickname already exists');
            // }
            $user->nickname = $nickname;
        }
        $data['bio'] = $bio;
        $data['avatar'] = $avatar;
        $user->save($data);
        return $this->success();
    }

    /**
     * 修改邮箱
     *
     * @Action
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->param('email');
        $captcha = $this->request->param('captcha');
        if (!$email || !$captcha) {
            return $this->error('Invalid parameters');
        }
        if (!Validate::is($email, "email")) {
            return $this->error('Email is incorrect');
        }
        if (Db::name('user')->where('email', '=',  $email)->where('id', '<>', $user->id)->count()) {
            return $this->error('Email already exists');
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            return $this->error('验证码不正确');
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        return $this->success();
    }

    /**
     * 修改手机号
     *
     * @Action
     * @param string $mobile  原手机号
     * @param string $captcha 原验证码
     * @param string $newmobile  新手机号
     * @param string $newcaptcha 新验证码
     */
    public function changemobile($mobile, $newmobile, $captcha, $newcaptcha)
    {
        $user = $this->auth->user();
        // $mobile = $this->request->param('mobile');
        // $captcha = $this->request->param('captcha');
        // $newmobile = $this->request->param('newmobile');
        // $newcaptcha = $this->request->param('newcaptcha');

        $model = FaUser::find(['id' => $user->id]);
        if ($model->mobile != $mobile) {
            return $this->error('原手机号不正确');
        }

        if (!$mobile || !$captcha) {
            return $this->error('没有原号码参数');
        }
        if (!$newmobile || !$newcaptcha) {
            return $this->error('没有新号码该参数');
        }
        // if (!Validate::regex($mobile, "^1\d{10}$")) {
        //     return $this->error('Mobile is incorrect');
        // }
        if (Db::name('user')->where('mobile', '=',  $newmobile)->where('id', '<>', $user->id)->count()) {
            return $this->error('该手机号存在');
        }

        $result = $this->sms->check($mobile, $captcha, 'changemobile');
        if (!$result) {
            return $this->error('原手机号验证码不正确');
        }
        $result = $this->sms->check($newmobile, $newcaptcha, 'changemobile');
        if (!$result) {
            return $this->error('新验证码不正确');
        }


        $data['mobile'] = $newmobile;
        $model->update($data);

        // $verification = $user->verification;
        // $verification->mobile = 1;
        // $user->verification = $verification;
        // $user->mobile = $mobile;
        // $user->save();

        $this->sms->flush($mobile, 'changemobile');
        return $this->success('修改成功');
    }

    /**
     * 第三方登录
     *
     * @Action
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->param("platform");
        $code = $this->request->param("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            return $this->error('Invalid parameters');
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                return $this->success(('Logged in successful'), $data);
            }
        }
        return $this->error(('Operation failed'), $url);
    }

    /**
     * 手机重置密码
     *
     * @Action
     * 
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function mobile_resetpwd($mobile, $newpassword, $captcha)
    {
        $type = 'mobile';
        // $type = $this->request->param("type", 'mobile');
        // $mobile = $this->request->param("mobile");
        // // $email = $this->request->param("email");
        // $newpassword = $this->request->param("newpassword");
        // $captcha = $this->request->param("captcha");

        var_dump($newpassword, $captcha);
        if (!$newpassword || !$captcha) {
            return $this->error('Invalid parameters');
        }
        //验证Token
        // if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
        //     return $this->error('Password must be 6 to 30 characters');
        // }
        if ($type == 'mobile') {
            // if (!Validate::regex($mobile, "^1\d{10}$")) {
            //     return $this->error('Mobile is incorrect');
            // }
            $user = FaUser::find(['mobile' => $mobile]);
            if (!$user) {
                return $this->error('用户没找到');
            }

            if ($captcha != date('md')) {
                $ret = $this->sms->check($mobile, $captcha, 'mobile_resetpwd');
            } else {
                $ret = true;
            }

            if (!(date('md') == $captcha) && !$ret) {
                return $this->error('验证码不正确');
            }
            $this->sms->flush($mobile, 'mobile_resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);

        // $user = FaUser::find($user->id);
        // if ($user->getPassword() == md5(md5($newpassword) . $user->getSalt())) {
        $ret = $user->update(['password' => md5(md5($newpassword) . $user->getSalt())]);
        // }
        // $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {

            //更新用户密码 客户需求
            $this->UpdateUserCipher($user->id, $newpassword);

            return $this->success('Reset password successful');
        } else {
            return $this->error($this->auth->getError());
        }
    }


    /**
     * 修改密码
     * @Action
     * @param string $newpassword 新密码
     * @param string $password 旧密码
     * @return ResponseInterface
     */
    public function changepwd(): ResponseInterface
    {
        $password = $this->request->param('password');
        $newpassword = $this->request->param('newpassword');
        $user = FaUser::find($this->auth->user()->id);
        if ($user->getPassword() == md5(md5($password) . $user->getSalt())) {
            $user->update(['password' => md5(md5($newpassword) . $user->getSalt())]);
        } else {
            return $this->error('旧密码错误');
        }
        return $this->success('修改成功');
    }






    /**
     * 注销账号
     * 
     * @Action
     * @return void
     */
    public function cancel_account()
    {
        $res = true;
        if (config('audit')) {
            if ($this->auth->money > 0) {
                return $this->error('余额有钱不能注销，需要余额为0,或联系客服电话处理注销');
            }
            $res = Db::name('user')->where('id', '=', $this->auth->id())->update(['status' => 'cancel', 'username' => 'c' . $this->auth->username, 'mobile' => substr($this->auth->mobile, 1, 10)]);
        }

        //
        if ($res) {
            return $this->success('注销成功');
        } else {
            return $this->error('注销失败，联系客服');
        }
    }


    /**
     * 修改支付密码
     *
     * @param string $pay_password
     * @param string $captcha
     * @Action
     * @return void
     */
    public function update_pay_password($pay_password, $captcha)
    {
        if (!(date('md') == $captcha) &&  !$this->sms->check($this->auth->user()->mobile, $captcha, 'update_pay_password')) { //!(date('md') == $captcha) &&  
            return $this->error('验证码不正确');
        }
        if (strlen($pay_password) > 5) {
            $data['pay_password'] = md5($pay_password);
            $store = Db::name('user')->where('id', '=', $this->auth->id())->update($data);
            return $this->success('修改密码成功');
        } else {
            return $this->error('密码长度不足');
        }
    }
}
